//
//  YTSettingsViewController.m
//  YiTuDriverClient
//
//  Created by 石少庸 on 2017/5/11.
//  Copyright © 2017年 Yitu. All rights reserved.
//

#import "YTSettingsViewController.h"
#import "YTUserLoginAPI.h"
#import "YTLoginViewController.h"
#import "YTNavigationController.h"

#import <XGPush/XGPush.h>
#import <JPush/JPUSHService.h>
#import <RongIMKit/RongIMKit.h>
#import <RongIMLib/RongIMLib.h>

@interface YTSettingsViewController ()
@property (weak, nonatomic) IBOutlet UIButton *logoutBtn;
@property (weak, nonatomic) IBOutlet UILabel *notifyText;
@property (assign, nonatomic) BOOL closed;
@end

@implementation YTSettingsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self checkRemoteNotification];
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIApplicationDidBecomeActiveNotification object:nil]
     subscribeNext:^(id x) {
         [self checkRemoteNotification];
    }];
}

- (IBAction)logoutAction:(UIButton *)sender {
    [UIAlertView bk_showAlertViewWithTitle:nil message:@"您确定要退出当前帐号么?"
                         cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"]
                                   handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
        if (buttonIndex) {
            [self userLogout];
        }
    }];
}

- (void)userLogout {
    [[YTUserLoginAPI userLogout] subscribeNext:^(id x) {
        [SVProgressHUD showSuccessWithStatus:@"退出成功"];
        [self performSegueWithIdentifier:@"YTLogout" sender:nil];
    } error:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"网络错误"];
    } completed:^{
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:kUserIdDefaults];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:kRongYunToken];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:kUserToken];
        [[NSUserDefaults standardUserDefaults] synchronize];
        // 断开推送
        [XGPush unRegisterDevice];
        // 断开IM
        [[RCIM sharedRCIM] logout];
        // 断开极光
//        [JPUSHService ]
    }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0 && _closed) {
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        [[UIApplication sharedApplication] openURL:url];
    }
}

/** 检测是否开启了通知*/
- (void)checkRemoteNotification {
    _closed = ([[[UIApplication sharedApplication] currentUserNotificationSettings] types] == 0);
    if (_closed) {
        _notifyText.text = @"未开启";
    } else {
        _notifyText.text = @"已开启";
    }
}

@end
